package com.project.poetry.common.job;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.project.poetry.service.entity.po.job.JobPO;
import com.project.poetry.service.entity.po.job.SysJobLogPO;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @author mengxj
 */
@Slf4j
public class ScheduleTask implements Runnable {

    private static final String SUCCESS = "success！";

    private static final String ERROR = "error！";

    private static final int MAX_LEN = 200;

    private Long jobId;

    private String descriptor;

    private String beanId;

    private String beanName;

    private String methodName;

    private String params;

    ScheduleTask(JobPO jobEntity){
        this.jobId = jobEntity.getId();
        this.descriptor = jobEntity.getDescriptor();
        this.beanId = jobEntity.getBeanId();
        this.beanName = jobEntity.getBeanName();
        this.methodName = jobEntity.getMethodName();
        this.params = jobEntity.getParams();
    }

    @Override
    public void run() {
        log.info("job start ==> beanId：{} beanName：{} methodName：{} params：{}", this.beanId, this.beanName, this.methodName, this.params);
        Exception ex = null;
        try {
            Class<?> cls;
            Object t;
            if(StrUtil.isNotBlank(this.beanName)){
                t = SpringContextUtils.getBean(this.beanName);
                cls = t.getClass();
            }else{
                cls = Class.forName(this.beanId);
                t = cls.newInstance();
            }
            if(StrUtil.isBlank(this.params)){
                Method method = cls.getDeclaredMethod(this.methodName);
                method.invoke(t);
            }else{
                Method method = cls.getDeclaredMethod(this.methodName, String.class);
                method.invoke(t, this.params);
            }
        }catch (Exception e){
            log.error("quartz job error！\n{}：{}", e.getClass(), e.getMessage());
            ex = e;
        }finally {
            try {
                this.saveLog(ex);
            }catch (Exception e){
                log.error("save log error！\n{}：{}", e.getClass(), e.getMessage());
            }
        }
    }

    private void saveLog(Exception ex){
        SysJobLogPO sysJobLog = new SysJobLogPO();
        sysJobLog.setJobId(this.jobId);
        sysJobLog.setDescriptor(this.descriptor);
        sysJobLog.setBeanId(this.beanId);
        sysJobLog.setBeanName(this.beanName);
        sysJobLog.setMethodName(this.methodName);
        sysJobLog.setParams(this.params);
        if(Objects.isNull(ex)){
            sysJobLog.setResult(SUCCESS);
        }else{
            sysJobLog.setResult(ERROR);
            String errorMsg = String.format("%s：%s", ex.getClass(), ex.getMessage());
            int len;
            sysJobLog.setErrorTip(errorMsg.substring(0,
                    (len = errorMsg.length()) > MAX_LEN ? MAX_LEN : len));
        }
        System.out.println(JSON.toJSONString(sysJobLog));
//        LogUtil.save(sysJobLog);
    }
}
